package com.google.code.tretris.rendering;

import java.util.List;

import android.content.Context;
import android.content.SharedPreferences;
import android.opengl.GLSurfaceView;
import android.util.Log;
import android.view.MotionEvent;

import com.google.code.tretris.SettingsDialog;
import com.google.code.tretris.Tretris;
import com.google.code.tretris.common.WKC;
import com.google.code.tretris.events.MoveEvent;
import com.google.code.tretris.events.UpdateBoardEvent;

public class TretrisView extends GLSurfaceView {

	private static final String LOG_TAG = TretrisView.class.getName();

	private final TretrisRenderer renderer;

	public interface MovementListener {
		public void onMovement(MoveEvent moveEvent);
	}
	
	private final String userId;
	private float lastX;
	private boolean rotate = false;
	private MovementListener movementListener;
	private final Shape activeShape;

	public TretrisView(Context context) {
		super(context);
		movementListener = (Tretris)context;

		SharedPreferences prefs = context.getSharedPreferences(
				SettingsDialog.PREFS_NAME, 0);
		userId = prefs.getString(SettingsDialog.USER_ID, "");
		//Scene scene = new Scene(userId);
		activeShape = new Shape();
		renderer = new TretrisRenderer(activeShape);
		setRenderer(renderer);
	}

	@Override
	public boolean onTouchEvent(final MotionEvent event) {

		final float x = event.getX();
		final float deltaX;		
		switch (event.getAction()) {		
		case MotionEvent.ACTION_MOVE:
			rotate = false;
			deltaX = lastX - x;			
			send(movement(deltaX));
			break;
		case MotionEvent.ACTION_DOWN:			
			lastX = x;
			rotate = true;
			return true;
		case MotionEvent.ACTION_UP:						
			if (rotate) {
				send(rotation());
			} else {
				deltaX = lastX - x;
				send(movement(deltaX));
			}
			rotate = false;
			break;
		default:
			break;
		}
		
		lastX = x;
		return true;
	}
	
	private void send(final MoveEvent event) {
		queueEvent(new Runnable() {
			public void run() {
				movementListener.onMovement(event);
			}
		});		
	}
	
	private MoveEvent movement(final float deltaX) {
		String user = Integer.toString(WKC.GRAPHICAL_CLIENT_IPC_UID);
		return (deltaX > 0) ? MoveEvent.left(user) : MoveEvent.right(user);
	}

	private MoveEvent rotation() {
		String user = Integer.toString(WKC.GRAPHICAL_CLIENT_IPC_UID);
		return MoveEvent.rotate(user);
		
	}
	public void onGameUpdate(final List<UpdateBoardEvent> events) {
		queueEvent(new Runnable() {
			public void run() {
				renderer.update(events);
			}
		});
	}

	public void onGameOver() {

	}	
}
